<template>
    <el-container>
        <el-main>
            <el-form ref="productForm" :model="form" label-width="100px">
                <div style="display: flex">

                    <el-form-item label="商品名称" style="width: 700px" prop="name" :rules="{ required: true, message: '请输入商品名称', trigger: 'blur' }">
                        <el-input v-model="form.name" />
                    </el-form-item>
                </div>
                <div style="display: flex">
                    <el-form-item label="商品类型" prop="type" style="width: 300px" :rules="{ required: true, message: '请选择商品类型', trigger: 'blur' }">
                        <el-select disabled v-model="form.type" placeholder="请选择" style="width:100%">
                            <el-option v-for="item in productTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品分类" style="width: 400px" prop="productCategoryId" :rules="{ required: true, message: '请选择商品分类', trigger: 'blur' }">
                        <el-cascader v-model="form.productCategoryId" style="width:100%" placeholder="请输入分类名" :options="productCategoryOptions" filterable clearable :show-all-levels="false" @change="productCategoryChange" />
                    </el-form-item>

                </div>
                <div style="display: flex">
                    <el-form-item label="运费模板" style="width: 300px">
                        <!--可搜索带选择框-->
                        <el-select v-model="form.freightId" style="width:100%" filterable clearable placeholder="请选择运费键字" :filter-method="searchFreight" :loading="freightLoading" @change="freightChange">
                            <el-option v-for="item in freightNames" :key="item.id" :label="item.name" :value="item.id" />
                            <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增运费 ---" value="/" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="主供应商" style="width: 400px" prop="supplierId">
                        <!--可搜索带选择框-->
                        <el-select v-model="supplierName" style="width:100%" filterable value-key="id" placeholder="请选择供应商关键字" :filter-method="searchSupp" :loading="suppLoading" @change="suppChange">
                            <el-option v-for="(item) in suppOptions" :key="item.id" :label="item.name" :value="item" />
                            <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增供应商 ---" value="#" />
                        </el-select>
                    </el-form-item>

                </div>
                <div style="display: flex">

                    <el-form-item label="配送方式" prop="shippingMethod" style="width: 300px">
                        <el-select v-model="form.shippingMethod" style="width: 100%" placeholder="请选择" multiple>
                            <el-option v-for="(item,index) in shippingMethodList" :key="index" :label="item.name" :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="商品标签" style="width: 400px">
                        <el-select v-model="tagIds" style="width: 100%" multiple placeholder="请选择">
                            <el-option v-for="(item,index) in tagOptions" :key="index" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </div>

                <el-tabs>
                    <!--tab1-->
                    <el-tab-pane label="SKU">
                        <!--商品规格-->
                        <el-row style="display: flex; justify-content: flex-end; position: relative;">
                            <span v-show="form.type !=2" class="el-icon-plus" style="position: absolute; top: -25px; left: 25px; color: #409EFF;" @click="addProduct" />
                            <el-col :span="23">
                                <meal type="edit" @mealSave="mealSave" :bom="bom" ref="meal" v-show="form.type ==2"></meal>
                                <el-table :data="productList" border stripe>
                                    <el-table-column label="货号/条码" width="130">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.sn" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="商品图片" width="80" align="center">
                                        <template slot-scope="{row}">
                                            <single-upload v-model="row.thumbnail" list-type="picture-card" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="规格" width="150">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.spec1" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="颜色" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.spec2" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="单位" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.unit" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="库存" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.stock" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>

                                    <el-table-column label="市场价" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.marketPrice" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="销售价" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>

                                    <el-table-column label="成本价" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.cost" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>0" :label="vips[0].name" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip1price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>1" :label="vips[1].name" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip2price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>2" :label="vips[2].name" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip3price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>3" :label="vips[3].name" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip4price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column v-if="vips.length>4" :label="vips[4].name" width="80">
                                        <template slot-scope="{row}">
                                            <el-input v-model="row.vip5price" @mousewheel.native.prevent @DOMMouseScroll.native.prevent type="number" />
                                        </template>
                                    </el-table-column>
                                    <el-table-column fixed="right" align="center" label="操作" width="80">
                                        <template v-if="!row.isList" slot-scope="{row}">
                                            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                                                <a @click="delProduct(row)">
                                                    <i style="color: #F56C6C" class="el-icon-delete" />
                                                </a>
                                            </el-tooltip>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                    <!--tab2-->
                    <el-tab-pane label="设置">
                        <div style="display: flex">
                            <el-form-item label="分销策略" style="width: 300px">
                                <el-select v-model="form.distributionId" style="width: 100%" clearable filterable :filter-method="queyrDisOptins" placeholder="请选择">
                                    <el-option v-for="item in disOptions" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>

                        </div>
                        <div style="display: flex">
                            <el-form-item label="最小订购量" style="width: 300px">
                                <el-input v-model="form.minLimit" type="number" @mousewheel.native.prevent />
                            </el-form-item>
                            <el-form-item label="每人限购量" style="width: 300px">
                                <el-input v-model="form.maxLimit" type="number" />
                            </el-form-item>
                        </div>


                        <div style="display: flex">

                            <el-form-item label="商品说明" style="width: 600px">
                                <el-input v-model="form.subTitle" placeholder="在商品以副标题形式展示" />
                            </el-form-item>

                        </div>

                      <div>
                        <el-form-item label="品牌类型" style="width: 300px">
                          <!--可搜索带选择框-->
                          <el-select v-model="form.brandId" style="width:100%" filterable placeholder="请选择品牌关键字" :filter-method="searchBrand" :loading="brandLoading" @change="brandChange">
                            <el-option v-for="item in barrelOptions" :key="item.id" :label="item.name" :value="item.id" />
                            <el-option style="background-color: #f9f9f9;text-align: center;" label="--- 新增品牌 ---" value="#" />
                          </el-select>
                        </el-form-item>
                      </div>

                      <div  style="display: flex">
                        <el-form-item label="重量(Kg)" style="width: 300px">
                          <el-input v-model="form.weight" type="number" @mousewheel.native.prevent />
                        </el-form-item>
                        <el-form-item label="保质期(天)" style="width: 300px">
                          <el-input v-model="form.quality" type="number" @mousewheel.native.prevent />
                        </el-form-item>
                      </div>


                    </el-tab-pane>

                    <el-tab-pane label="详情">
                        <div class="menu-wrapper">
                            <tinymce v-model="article.content" :height="300" :width="950" />
                            <el-row>
                                <div class="photo-content">
                                    <div style="margin-top: 20px">
                                        <span style="font-size: 18px;color:#409EFF;">轮播图(最多五张)</span>
                                    </div>
                                </div>
                                <el-col :span="15">
                                    <multiUploadDraggable v-model="article.productMeta.images" />
                                </el-col>
                            </el-row>

                            <el-row>
                                <div class="photo-content">
                                    <div style="margin-top: 20px;">
                                        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">视频介绍</span>
                                    </div>
                                </div>
                                <el-col :span="8">
                                    <video-upload v-model="article.productMeta.video" />
                                </el-col>
                            </el-row>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <el-form-item>
                    <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="editProduct('productForm')">
                        &nbsp&nbsp完 成&nbsp&nbsp
                    </el-button>
                </el-form-item>

            </el-form>
            <category-dialog ref="categoryDialog" request="productCategory" @confirm="categoryDialogConfirm" />

            <el-dialog v-el-drag-dialog title="添加品牌" :visible.sync="brandVisible" width="50%" :before-close="brandClose">
                <div style="height: 70vh;overflow: auto;position: relative;">
                    <brandAdd :is-dialog="true" @confirm="brandAddConfirm" />
                </div>
            </el-dialog>
            <el-dialog v-el-drag-dialog title="添加供应商" :visible.sync="suppVisible" width="50%" :before-close="suppClose">
                <div style="height: 70vh;overflow: auto;position: relative;">
                    <suppAdd :is-dialog="true" @confirm="suppAddConfirm" />
                </div>
            </el-dialog>
            <addFreight ref="freight" />
        </el-main>
    </el-container>
</template>
<style lang="scss" scoped>
.photo-content {
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
}
/deep/.el-input__inner {
    padding: 0 5px;
}
/deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
    .menu-wrapper {
        margin: 15px;
    }
}
</style>
<script>
import { mapGetters } from "vuex";
import { list as vipList } from "@/api/vip";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import MultiUpload from "@/components/Upload/multiUpload";
import multiUploadDraggable from "@/components/Upload/multiUploadDraggable";

import VideoUpload from "@/components/Upload/videoUpload";
import Tinymce from "@/components/Tinymce";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { EventBus } from "@/api/eventBus";
import utils from "../../utils/utils.js";
import { list as freightList } from "@/api/freight";
import { find, update } from "@/api/product";
import { find as findInfo, update as updateInfo } from "@/api/productArticle";
import { list as tagList } from "@/api/tag";
import { list as brandList } from "@/api/brand";
import { list as suppList } from "@/api/supplier";
import { list as productCategoryList } from "@/api/productCategory";
import CategoryDialog from "@/components/CategoryDialog";
import SingleUpload from "@/components/Upload/singleUpload";
import brandAdd from "../brand/add.vue";
import suppAdd from "../supplier/add.vue";
import addFreight from "../freight/add";
import { list as distributionList } from "@/api/distribution.js";
import { getMenuTree as MenuTree } from "@/api/sysMch";
import { list as memberList } from "@/api/member";
import { list as shoplist } from "@/api/shop";
import meal from "./component/meal.vue";
export default {
    name: "product-edit",
    directives: { elDragDialog, permission },
    filters: {},
    components: {
        CategoryDialog,
        SingleUpload,
        brandAdd,
        suppAdd,
        MultiUpload,
        VideoUpload,
        Tinymce,
        addFreight,
        multiUploadDraggable,
        meal,
    },
    data() {
        return {
            id: "",
            vips: [],
            length: 0,
            times: null,
            isCount: true,
            shippingMethods: [],
            productCategoryOptions: [],
            clicked: false, // 按钮防双击
            categoryName: "",
            subscribe: false,
            market: false,
            shippingMethodList: [
                { name: "普通快递", value: "0" },
                { name: "同城配送", value: "2" },
                { name: "到店提货", value: "1" },
            ],
            tempType: "",
            typeDisabled: false,
            productTypeOptions: [
                { id: 0, name: "普通商品" },
                { id: 1, name: "虚拟商品" },
                { id: 2, name: "套餐商品" },
                { id: 3, name: "兑换商品" },
            ],
            article: {
                id: "",
                goods: "",
                productMeta: {
                    label: "",

                    images: [],
                    video: "",
                },
                content: "",
            },
            form: {
                maxLimit: "",
                publishType: 0,
                id: "",
                name: "",
                productCategoryId: "",
                shortName: "",
                orders: "",
                type: "",
                freightId: "",
                shippingMethod: [],
                isMarketable: false,
                subTitle: "",
                minLimit: "",
                // labal: '',
                quality: "",
                distributionId: "",
                brandId: "",
                stock: "",
                supplierId: "",
                allocatedStock: "",
                weight: "",
                goodsId: "",
            },
            tagIds: [],
            disOptions: [],
            tagOptions: [],
            freightNames: [],
            brandLoading: false,
            freightLoading: false,
            brandVisible: false,
            barrelOptions: [],
            suppOptions: [],
            suppLoading: false,
            suppVisible: false,
            supplierName: "",
            brandName: "",
            productList: [
                {
                    isClick: false,
                    isFirst: true,
                    maxLimit: "",
                    length: 0,
                    publishType: 0,
                    isList: true,
                    name: "",
                    productCategoryId: "",
                    shortName: "",
                    orders: 0,
                    type: "",
                    freightId: "",
                    isMarketable: false,
                    subTitle: "",
                    minLimit: "",
                    // labal: '',
                    quality: "",
                    isChose: false,
                    isCount: false,
                    distributionId: "",
                    brandId: "",
                    stock: "",
                    supplierId: "",
                    allocatedStock: "",
                    weight: "",
                    subType: 0,
                    shippingMethod: "",
                    // ------
                    sn: "",
                    thumbnail: "",
                    spec1: "",
                    spec2: "",
                    unit: "",
                    unitRate: "",
                    marketPrice: "",
                    price: "",
                    cost: "",
                    unitType: "",
                    vip1price: "",
                    vip2price: "",
                    vip3price: "",
                    vip4price: "",
                    vip5price: "",
                    article: {
                        productMeta: {
                            images: [],
                            video: "",
                            label: "",
                        },
                        content: "",
                    },
                },
            ],
            bom: {},
            type: null,
        };
    },
    watch: {
        // 路由地址不变的情况下,如果id变化则重新获取数据
        $route(newVal, oldVal) {
            console.log(newVal);
            if (newVal.name == "product-edit" && newVal.query.id != this.id) {
                this.getFindData();
            }
        },
    },
    computed: {
        ...mapGetters(["scopeType"]),
    },
    created() {
        this.type = this.$route.query.type;
        console.log("55555555555554444444444444");
        console.log(this.type);
        EventBus.$on("freight-add", (res) => {
            // 监听新增完毕
            // 更新列表数组
            this.freightNames.splice(0, 0, res);
        });
        this.loadMenuTree();
        this.loadVip();
        this.loadFright("");
        this.loadTag();
        this.loadBrand("");
        this.loadSupp("");
        this.loadDistribution("");
        this.getFindData();
        this.loadProductCategory();
    },
    activated() {},
    methods: {
        loadMenuTree() {
            if (this.scopeType == 3) {
                this.productTypeOptions.push({
                    id: 4,
                    name: "桶装水(不含一次性桶) ",
                });
            }
        },
        getFindData() {
            this.times = new Date().getSeconds();
            this.id = this.$route.query.id;
            var _this = this;
            find(this.id)
                .then((response) => {
                    console.log(response);
                    _this.article = response.data.article;
                    _this.length = response.data.products.length - 1;
                    for (var k = 0; k < response.data.products.length; k++) {
                        this.length = k;
                        response.data.products[k]["length"] = this.length;
                    }
                    for (var i = 1; i < response.data.products.length; i++) {
                        if (response.data.products[i].unitType == 2) {
                            response.data.products[i]["isCount"] = false;
                        } else {
                            response.data.products[i]["isCount"] = true;
                        }
                        if (response.data.products[0].unitType == 0) {
                            response.data.products[i]["isClick"] = true;
                            response.data.products[i]["isChose"] = true;
                        } else {
                            response.data.products[i]["isClick"] = false;
                            response.data.products[i]["isChose"] = false;
                        }
                    }

                    response.data.products[0]["isFirst"] = true;

                    _this.productList = response.data.products;
                    _this.tagIds = [];
                    if (!utils.isNull(this.productList[0].tags)) {
                        _this.productList[0].tags.forEach(function (item) {
                            _this.tagIds.push(item.id);
                        });
                    }

                    this.productList.forEach((item) => {
                        if (item.isList) {
                            this.form.maxLimit = item.maxLimit;
                            this.form.id = item.id;
                            this.form.name = item.name;
                            this.categoryName = item.productCategoryName;
                            this.form.productCategoryId =
                                item.productCategoryId;
                            this.form.shortName = item.shortName;
                            this.form.orders = item.orders;
                            this.form.publishType = item.publishType;
                            //this.form.type = item.type;
                            if (item.subType == 2) {
                                this.typeDisabled = true;
                            }
                            if (item.type == 0 && item.subType == 0) {
                                this.form.type = 0;
                            } else if (item.type == 1 && item.subType == 0) {
                                this.form.type = 1;
                            } else if (item.type == 1 && item.subType == 1) {
                                this.form.type = 2;
                            } else if (item.type == 2 && item.subType == 0) {
                                this.form.type = 3;
                            } else if (item.type == 0 && item.subType == 4) {
                                this.form.type = 4;
                            }
                            this.form.isMarketable = item.isMarketable;
                            this.form.subTitle = item.subTitle;
                            this.form.minLimit = item.minLimit;
                            this.form.quality = item.quality;
                            this.form.distributionId = item.distributionId;
                            this.form.brandId = item.brandId;
                            this.form.stock = item.stock;
                            this.form.supplierId = JSON.stringify(
                                item.supplierId
                            );
                            this.form.allocatedStock = item.allocatedStock;
                            this.form.weight = item.weight;
                            this.form.goodsId = item.goodsId;
                            this.form.freightId = item.freightId;
                            if (item.shippingMethod) {
                                if (!utils.isNull(item.shippingMethod)) {
                                    _this.form.shippingMethod =
                                        item.shippingMethod.split(",");
                                } else {
                                    _this.form.shippingMethod = ["0"];
                                }
                            } else {
                                _this.form.shippingMethod = ["0"];
                            }
                        }
                    });
                    this.supplierName = response.data.supplierName;
                    this.brandName = response.data.brandName;
                    if (
                        response.data.products[0].type == 1 &&
                        response.data.products[0].subType == 1
                    ) {
                        _this.bom = response.data.products[0].bom;
                        _this.$refs.meal.addShowDialog(_this.bom);
                        console.log(_this.bom);
                        console.log("套餐");
                    }
                    console.log(_this.form);
                })
                .catch((error) => {
                    console.log(error.content);
                });
        },
        loadDistribution(query) {
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 50);
            params.append("name", query);
            distributionList(params)
                .then((res) => {
                    this.disOptions = res.data.data;
                    console.log(res, "分销");
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        queyrDisOptins(query) {
            this.loadDistribution(query);
        },
        // 商品分类选择事件
        productCategoryChange(val) {
            this.form.productCategoryId = val[val.length - 1];
        },
        // 加载商品分类的数据
        loadProductCategory() {
            productCategoryList()
                .then((response) => {
                    this.productCategoryOptions =
                        this.formatProductCategoryData(response.data);
                })
                .catch((error) => {});
        },
        // 整理商品分类数据
        formatProductCategoryData(data) {
            const _this = this;
            const productCategoryOptions = [];
            if (data.length > 0) {
                data.map((item) => {
                    const productCategoryOptionsItem = {};
                    productCategoryOptionsItem.value = item.id;
                    productCategoryOptionsItem.label = item.name;
                    if (item.childrens.length > 0) {
                        productCategoryOptionsItem.children =
                            _this.formatProductCategoryData(item.childrens);
                    }
                    productCategoryOptions.push(productCategoryOptionsItem);
                });
            }
            return productCategoryOptions;
        },
        loadVip() {
            vipList({ vipType: 0 }).then((res) => {
                res.data.data.forEach((item) => {
                    if (item.vip > 0) {
                        this.vips.push(item);
                    }
                });
                this.vips = this.vips.sort(this.compare("vip", true));
            });
        },
        compare(property, desc) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                if (desc == true) {
                    // 升序排列
                    return value1 - value2;
                } else {
                    // 降序排列
                    return value2 - value1;
                }
            };
        },
        loadFright(query) {
            const params = new URLSearchParams();
            params.append("name", query);
            params.append("pageNum", 1);
            params.append("pageSize", 1000);
            this.freightLoading = true;
            freightList(params)
                .then((response) => {
                    this.freightLoading = false;
                    this.freightNames = response.data.data;
                })
                .catch((error) => {
                    this.freightLoading = false;
                });
        },
        searchFreight(query) {
            if (query.length < 2) {
                this.$message.error("不得少于两个字符");
                return;
            }
            this.loadFright(query);
        },
        loadTag() {
            const _this = this;
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 1000);
            params.append("type", 3);
            tagList(params)
                .then((response) => {
                    console.log(response);
                    _this.tagOptions = response.data.data;
                })
                .catch((error) => {});
        },
        dialogShow() {
            console.log("点击了");
            this.$refs.categoryDialog.show();
        },
        categoryDialogConfirm(val) {
            this.form.productCategoryId = val.id;
            this.categoryName = val.name;
        },
        freightChange(val) {
            if (val == "/") {
                this.form.freightId = "";
                this.$refs.freight.dialogFormVisible = true;
                this.$refs.freight.addFreightClick();
            }
        },
        loadBrand(query) {
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 50);
            params.append("name", query);
            this.brandLoading = true;
            brandList(params)
                .then((response) => {
                    console.log(response);
                    this.brandLoading = false;
                    this.barrelOptions = response.data.data;
                    this.setAddClickHeight();
                })
                .catch((error) => {
                    this.brandLoading = false;
                });
        },
        searchBrand(query) {
            if (query.length < 2) {
                this.$message.error("不得少于两个字符");
                return;
            }
            this.loadBrand(query);
        },
        brandChange(val) {
            if (val == "#") {
                this.form.brandId = "";
                this.brandVisible = true;
            } else {
                this.form.brandId = val;
            }
        },
        brandClose() {
            this.brandVisible = false;
        },
        brandAddConfirm(val) {
            this.barrelOptions.push(val);
            this.form.brandId = val.id;
            this.brandVisible = false;
        },
        loadSupp(query) {
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 10);
            params.append("name", query);
            this.suppLoading = true;
            suppList(params)
                .then((response) => {
                    console.log(response);
                    this.suppLoading = false;
                    this.suppOptions = response.data.data;
                })
                .catch((error) => {
                    this.suppLoading = false;
                });
        },
        suppChange(val) {
            console.log(val);
            if (val == "#") {
                this.form.supplierId = "";
                this.suppVisible = true;
            } else {
                this.form.supplierId = val.id;
            }
        },
        searchSupp(query) {
            if (query.length < 2) {
                this.$message.error("不得少于两个字符");
                return;
            }
            this.loadSupp(query);
        },
        suppClose() {
            this.suppVisible = false;
        },
        suppAddConfirm(val) {
            this.suppOptions.push(val);
            this.form.supplierId = val.id;
            this.suppVisible = false;
        },
        chooseUnitType(data) {
            if (
                this.productList.length > 1 &&
                this.productList[0].unitType === 1
            ) {
                if (this.productList[data].unitType === 2) {
                    for (var l = 1; l < this.productList.length; l++) {
                        this.productList[l].isCount = true;
                    }
                    this.productList[data].isCount = false;
                    console.log(this.productList);
                } else {
                    for (var v = 1; v < this.productList.length; v++) {
                        this.productList[v].isCount = false;
                    }
                }
            }

            if (this.productList.length > 1) {
                if (this.productList[0].unitType == 0) {
                    for (var i = 1; i < this.productList.length; i++) {
                        this.productList[i].unitType = 0;
                        this.productList[i].isChose = true;
                    }
                } else {
                    for (var i = 1; i < this.productList.length; i++) {
                        this.productList[i].isChose = false;
                    }
                }
            }
        },
        addProduct() {
            this.length += 1;
            this.productList.push({
                isList: false,
                name: "",
                isClick: true,
                productCategoryId: "",
                shortName: "",
                orders: 0,
                isFirst: false,
                length: this.length,
                type: "0",
                publishType: 0,
                isCount: this.isCount,
                isMarketable: false,
                subTitle: "",
                freightId: "",
                minLimit: "",
                maxLimit: "",
                quality: "",
                shippingMethod: "",
                distributionId: "",
                brandId: "",
                stock: "",
                supplierId: "",
                allocatedStock: "",
                weight: "",
                subType: "",
                // -----
                sn: this.productList[0].sn,
                thumbnail: this.productList[0].thumbnail,
                spec1: this.productList[0].spec1,
                spec2: this.productList[0].spec2,
                unit: this.productList[0].unit,
                unitRate: this.productList[0].unitRate,
                marketPrice: this.productList[0].marketPrice,
                price: this.productList[0].price,
                cost: this.productList[0].cost,
                unitType: "",
                vip1price: this.productList[0].vip1price,
                vip2price: this.productList[0].vip2price,
                vip3price: this.productList[0].vip3price,
                vip4price: this.productList[0].vip4price,
                vip5price: this.productList[0].vip5price,
                isChose: false,
                article: {
                    productMeta: {
                        label: "",
                        images: [],
                        video: "",
                    },
                    content: "",
                },
            });
            if (
                this.productList.length > 1 &&
                this.productList[0].unitType === 1
            ) {
                for (var l = 1; l < this.productList.length; l++) {
                    if (this.productList[l].unitType === 2) {
                        this.productList[this.length].isCount = true;
                    }
                }
            }
            if (this.productList.length > 1) {
                if (this.productList[0].unitType === 0) {
                    for (var i = 1; i < this.productList.length; i++) {
                        this.productList[i].unitType = 0;
                        this.productList[i].isChose = true;
                    }
                }
            }
            this.setAddClickHeight();
        },
        delProduct(row) {
            var index = this.productList.indexOf(row);
            if (index !== -1) {
                this.productList.splice(index, 1);
            }
            this.setAddClickHeight();
        },
        editProduct(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                if (valid) {
                    // 校验表单
                    if (_this.form.type == 2) {
                        _this.$refs.meal.addClick();
                        return;
                    }
                    _this.createdProduct();
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        setAddClickHeight() {
            setTimeout(() => {
                // 获取表头的高度
                const tableTopHeight = document.querySelector(
                    ".el-table__header-wrapper"
                ).offsetHeight;
                // 获取一行表格高度
                const tableHeight =
                    document.querySelector(".el-table__row").offsetHeight;
                // 获取添加按钮样式
                const addClickStyle = document.querySelector(".el-icon-plus");
                // 获取添加按钮高度
                const addClickHeight = addClickStyle.offsetHeight;
                // 设置添加按钮的位置
                const moveHeight =
                    tableTopHeight +
                    (this.productList.length - 1) * tableHeight +
                    (tableHeight - addClickHeight) / 2;
                addClickStyle.style.top = moveHeight + "px";
            }, 100);
        },
        mealSave(data) {
            if (data != "1") {
                console.log(data);
                console.log("套餐");
                this.bom = data
                this.createdProduct();
            }
        },
        createdProduct() {
            var _this = this;
            _this.clicked = true;
            const params = new URLSearchParams();
            _this.tagIds.forEach(function (item) {
                params.append("tagIds", item);
            });
            if (
                this.productList[0].unitType != 0 &&
                this.productList.length == 1
            ) {
                _this.$message({
                    message: "已启用多单位，商品规格不足",
                    type: "error",
                });
                _this.clicked = false;
                return;
            }
            for (let i = 0; i < _this.productList.length; i++) {
                delete this.productList[i].length;
                if (this.productList[i].hasOwnProperty("isFirst")) {
                    delete this.productList[i].isFirst;
                }
                if (this.productList[i].hasOwnProperty("isChose")) {
                    delete this.productList[i].isChose;
                }
                if (this.productList[i].hasOwnProperty("isCount")) {
                    delete this.productList[i].isCount;
                }
                if (this.productList[i].hasOwnProperty("isClick")) {
                    delete this.productList[i].isClick;
                }
                _this.productList[i].name = _this.form.name;
                _this.productList[i].productCategoryId =
                    _this.form.productCategoryId;
                _this.productList[i].shortName = _this.form.shortName;
                _this.productList[i].orders = _this.form.orders;
                if (_this.form.type == 0) {
                    //普通商品
                    _this.productList[i].type = 0;
                    _this.productList[i].subType = 0;
                } else if (_this.form.type == 1) {
                    //虚拟商品
                    _this.productList[i].type = 1;
                    _this.productList[i].subType = 0;
                } else if (_this.form.type == 2) {
                    //套餐商品
                    _this.productList[i].type = 1;
                    _this.productList[i].subType = 1;
                    _this.productList[i].bom = _this.bom
                } else if (_this.form.type == 3) {
                    //购物券商品
                    _this.productList[i].type = 2;
                    _this.productList[i].subType = 0;
                } else if (_this.form.type == 4) {
                    //桶装水
                    _this.productList[i].type = 0;
                    _this.productList[i].subType = 4;
                } else if (_this.form.type == 5) {
                    //桶装水
                    _this.productList[i].type = 2;
                    _this.productList[i].subType = 0;
                }
                _this.productList[i].publishType = _this.form.publishType;
                _this.productList[i].isMarketable = false;
                _this.productList[i].freightId = _this.form.freightId;
                _this.productList[i].subTitle = _this.form.subTitle;
                _this.productList[i].minLimit = _this.form.minLimit;
                _this.productList[i].maxLimit = _this.form.maxLimit;
                _this.productList[i].quality = _this.form.quality;
                _this.productList[i].distributionId = _this.form.distributionId;
                _this.productList[i].brandId = _this.form.brandId;
                _this.productList[i].supplierId = _this.form.supplierId;
                _this.productList[i].allocatedStock = _this.form.allocatedStock;
                _this.productList[i].weight = _this.form.weight;
                _this.productList[i].goodsId = _this.form.goodsId;
                _this.productList[i].article = _this.article;
                _this.productList[i].shippingMethod =
                    _this.form.shippingMethod.toString();
                if (
                    parseInt(_this.productList[i].minLimit) != 0 &&
                    parseInt(_this.productList[i].maxLimit) != 0 &&
                    parseInt(_this.productList[i].minLimit) >
                        parseInt(_this.productList[i].maxLimit)
                ) {
                    _this.$message({
                        message: "最小订购量不可大于每日限量",
                        type: "success",
                    });
                    _this.clicked = false;
                    return;
                }
                if (_this.productList[i].sn == "") {
                    _this.$message({
                        message: "请完善货号/条码",
                        type: "error",
                    });
                    _this.clicked = false;
                    return;
                }
                if (utils.isNull(_this.productList[i].unit)) {
                    _this.productList[i].unit = "件";
                }
                if (utils.isNull(_this.productList[i].unitRate)) {
                    _this.productList[i].unitRate = 1;
                }
                if (utils.isNull(_this.productList[i].thumbnail)) {
                    _this.productList[i].thumbnail =
                        "http://cdn.rzico.com/weex/resources/images/defaultProduct.png";
                }
                if (utils.isNull(_this.productList[i].weight)) {
                    _this.productList[i].weight = 0;
                }
                if (utils.isNull(_this.productList[i].allocatedStock)) {
                    _this.productList[i].allocatedStock = 0;
                }
                if (utils.isNull(_this.productList[i].stock)) {
                    _this.productList[i].stock = 0;
                }
                if (utils.isNull(_this.productList[i].quality)) {
                    _this.productList[i].quality = 0;
                }
                if (
                    utils.isNull(_this.productList[i].minLimit) ||
                    _this.productList[i].minLimit < 1
                ) {
                    _this.productList[i].minLimit = 1;
                }
                if (utils.isNull(_this.productList[i].marketPrice)) {
                    _this.productList[i].marketPrice = 0;
                }
                if (utils.isNull(_this.productList[i].price)) {
                    _this.productList[i].price = 0;
                }
                if (utils.isNull(_this.productList[i].cost)) {
                    _this.productList[i].cost = 0;
                }
                if (utils.isNull(_this.productList[i].vip1price)) {
                    _this.productList[i].vip1price = 0;
                }
                if (utils.isNull(_this.productList[i].vip2price)) {
                    _this.productList[i].vip2price = 0;
                }
                if (utils.isNull(_this.productList[i].vip3price)) {
                    _this.productList[i].vip3price = 0;
                }
                if (utils.isNull(_this.productList[i].vip4price)) {
                    _this.productList[i].vip4price = 0;
                }
                if (utils.isNull(_this.productList[i].vip5price)) {
                    _this.productList[i].vip5price = 0;
                }

            }
            console.log(this.productList);
            update(_this.productList, params)
                .then((response) => {
                    console.log(response);
                    _this.clicked = false;
                    EventBus.$emit("product-edit", response.data[0]);

                    if (this.type == "water") {
                        _this.$store
                            .dispatch("tagsView/delView", _this.$route)
                            .then(({ visitedViews }) => {
                                _this.$router.push({
                                    path: "/waterTicket/list",
                                });
                            }); // 关闭当前tab回到列表
                    } else {
                        _this.$store
                            .dispatch("tagsView/delView", _this.$route)
                            .then(({ visitedViews }) => {
                                _this.$router.push({
                                    path: "/product/list",
                                });
                            }); // 关闭当前tab回到列表
                    }
                })
                .catch((error) => {
                    _this.clicked = false;
                });
        },
    },
};
</script>
